import { Api } from "../../../../utils/api.js"
import { Http } from '../../../../utils/http.js'
import { AccurateMath } from "../../../../utils/accurateMath.js"
import { TimeToDate } from '../../../../utils/timeToDate.js'
let timeToDate = new TimeToDate()
const http = new Http()
const accurateMath = new AccurateMath()
const pageSize = 6

// pages/me/order/orderList/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    orderType: {
      type: Number,
      value: 0
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    orders: [],
    pageNum: 1,
    pages: 1,
    showMask: false,
    selectOrder: null,
    interval: null
  },

  attached: function() {
    this.getOrderList(false, false)
  },

  /**
   * 组件的方法列表
   * @param isPullToRefresh： 是否是滑动刷新
   * @param isLoadMore： 是否是下拉加载数据
   */
  methods: {
    getOrderList: function(isPullToRefresh, isLoadMore){
      if(!isPullToRefresh){
        wx.showLoading({
          title: "加载中..."
        })
      }
      if(!isLoadMore){
        this.setData({
          pageNum: 1,
          pages:1
        })
      }
      if (this.data.pageNum <= this.data.pages){
        var that = this
        http.sendHttp(Api.get_orders, {
          data: {
            type: this.data.orderType,
            pageNum: this.data.pageNum,
            pageSize: pageSize
          },
          success: function (res) {
            var orders = res.data.obj.orders
            that.setData({
              pageNum: that.data.pageNum + 1,
              pages: res.data.obj.pages
            })
            if (orders != null && orders.length > 0) {
              orders = that.calculate(orders)
              var lastOrders = that.data.orders
              if (!isLoadMore) {
                lastOrders = []
              }
              lastOrders = lastOrders.concat(orders)
              that.setData({
                orders: lastOrders
              })
              that.calExpiredTime()
            }
          },
          finish: function () {
            wx.hideLoading()
          }
        })
      }
    },

    calculate: function(orders){
      if(orders != null && orders.length > 0){
        orders.forEach( item => {
          var goodList = item.goodsList
          var number = 0
          if(goodList != null && goodList.length > 0){
            goodList.forEach(item => {
              number = accurateMath.accAdd(item.number, number)
            })
          }
          item.number = number
          item.tmCreate = timeToDate.formatTime(item.tmCreate / 1000, 'Y-M-D h:m')
          item.amount = accurateMath.accSub(item.amount, item.amountAgio)
        })
      }
      return orders
    },

    scrollToLower: function (event) {
      if(this.data.pageNum <= this.data.pages){
        this.getOrderList(true, true)
      }
    },

    tapDelete: function (event) {
      var that = this
      var index = event.currentTarget.dataset.idx
      var order = this.data.orders[index]
      wx.showModal({
        title: '提示',
        content: '是否删除订单：' + order.orderNo,
        success: function(res){
          if(res.confirm){
            wx.showToast({
              title: "删除成功！"
            })
            that.deleteOrder(order.id, index)
          }
        }
      })
    },

    deleteOrder: function(orderId, index){
      var that = this
      http.sendHttp(Api.del_order, {
        data:{
          orderId: orderId
        },
        success:function(){
          var orders = that.data.orders
          orders.splice(index, 1)
          that.setData({
            orders: orders
          })
        }
      }, "POST")
    },
    tapShowLogistics: function(event){
      var orderIndex = event.currentTarget.dataset.idx
      var order = this.data.orders[orderIndex]
      this.triggerEvent('showLogistics', {
        selectOrder: order
      })
    },

    repay: function (e) {
      var idx = e.currentTarget.dataset.idx
      var order = this.data.orders[idx]
      this.triggerEvent('repay', {
        order: order
      })
    },

    confirmReceipt: function (e) {
      var that = this
      wx.showModal({
        title: '提示',
        content: '是否确认收货？',
        success(res) {
          if (res.confirm) {
            var idx = e.currentTarget.dataset.idx
            var order = that.data.orders[idx]
            that.receipt(order, idx)
          }
        }
      })
    },

    calExpiredTime: function() {
      let that = this
      if (this.data.interval == null) {
        let interval = setInterval(function () {
          let orders = that.data.orders
          if (orders.length > 0) {
            orders.forEach((item, index) => {
              if (item.state == 1 && item.tmExpired > 0) {
                let tmExpired = item.tmExpired - 1000
                let paramName1 = `orders[${index}].dateExpired`
                let paramName2 = `orders[${index}].tmExpired`
                let min = Math.floor(tmExpired / 60000)
                min = min < 10 ? '0' + min : min
                let sec = parseInt(tmExpired / 1000 % 60)
                sec = sec < 10 ? '0' + sec : sec
                that.setData({
                  [paramName1]: min + ':' + sec,
                  [paramName2]: tmExpired,
                })
              }
            })
          }
        }, 1000)
        this.setData({
          interval: interval
        })
      }
    },

    receipt: function (order, idx) {
      var that = this
      var orderId = order.id
      http.sendHttp(Api.confirm_receipt_order, {
        data: {
          orderId: orderId
        },
        success: function (res) {
          wx.showToast({
            title: '收货成功',
          })
          var orderList = that.data.orders
          orderList.splice(idx, 1)
          that.setData({
            orders: orderList
          })
        }
      }, 'POST')
    },

    toShop: function(){
      wx.switchTab({
        url: '/pages/mall/index/index'
      })
    },

    cancelOrder: function (e) {
      var that = this
      wx.showModal({
        title: '提示',
        content: '是否确定取消订单？',
        success(res) {
          var index = e.currentTarget.dataset.idx
          var orders = that.data.orders
          if (res.confirm) {
            http.sendHttp(Api.cancel_order, {
              data: {
                orderId: orders[index].id
              },
              success: function (res) {
                orders.splice(index, 1)
                that.setData({
                  orders: orders
                })
              }
            }, 'POST')
          }
        }
      })
    }
  }
})
